#include "XSystem/XCore.h"
#include "Core.h"

using namespace std;

XResourcesManager data;

// Network receive thread
void NetworkReceiveThreadFunc(void* UserData)
{
	while (1)
	{
		data.ReceivePackets();
	}
}

// Network send thread
void NetworkSendThreadFunc(void* UserData)
{
	while (1)
	{
		sf::Sleep(0.001f);

		data.SendPackets();
	}
}

int main()
{	
	// Default window
	sf::RenderWindow app(sf::VideoMode(800, 600, 32), "-");

	// Load the resources manager
	data.Init(&app);
	data.DisplayLogs(true);

	// Create the window
	app.Create(sf::VideoMode(data.GetInt("resolutionX"), data.GetInt("resolutionY"), 32), "Project-RoFL Client");
	app.SetFramerateLimit(60);

	// Debug: build version
	data.SetString("version", "v0.0.0004");
	data.NewLog("Program version '"+data.GetString("version")+"'");

	// Network initializing
	sf::Thread NetworkReceiveThread(&NetworkReceiveThreadFunc);
    NetworkReceiveThread.Launch();
	sf::Thread NetworkSendThread(&NetworkSendThreadFunc);
    NetworkSendThread.Launch();

	// Create the interface (ui)
	XUserInterface ui(&data);
	
	ui.AddWindow(new GPopup(&data), "popup");
	ui.AddWindow(new GLoginBackground(&data), "loginbg");
	ui.AddWindow(new GLogin(&data), "login");
	ui.AddWindow(new GSelectChar(&data), "selectchar");
	ui.AddWindow(new GMain(&data), "main");
	ui.AddWindow(new GInventory(&data), "inventory");

	ui.AddScreen("login", "loginbg;login;");
	ui.AddScreen("selectchar", "loginbg;selectchar;");
	ui.AddScreen("main", "main;");

	ui.SetScreen("login");

	// Connect to server
	if (!data.Connect())
	{
		app.Close();
	}

	// Main loop
	const sf::Input& input = app.GetInput();
	while(app.IsOpened())
	{
		// Check events
		sf::Event Event;
		while(app.GetEvent(Event))
		{
			if(Event.Type == sf::Event::Closed)
				app.Close();

			ui.CheckEvent(Event);
		}

		// Check input
		ui.CheckState(input);

		// Check functions
		ui.CheckFunctions();

		// Clear
		//app.Clear();

		// Draws
		ui.Draw();

		// Display
		app.Display();
	}

	// Erase data and close down
	NetworkReceiveThread.Terminate();
	NetworkSendThread.Terminate();
	data.Close();
	data.SendPackets();

	return 0;
}
